import {Component, OnInit} from '@angular/core';
import {Roleinfo, RoleService} from "../role.service";
import {FormGroup, FormControl} from "@angular/forms";
import {Router} from "@angular/router";

@Component({
  selector: 'app-mylogin',
  templateUrl: './mylogin.component.html',
  styleUrl: './mylogin.component.css'
})
export class MyloginComponent implements OnInit {
  roleinfo: Roleinfo[] = [];
  data4Login = new FormGroup({
    name: new FormControl(''),
    password: new FormControl(''),
    roleId: new FormControl(0)
  });
  responseBody = '';
  responseHeader = '';

  constructor(private rolesService: RoleService,private router:Router) {
  }


  ngOnInit(): void {
    this.rolesService.getRoleinfo().subscribe(
      roles => {
        this.roleinfo = roles;
      }
    );
  }

  submitForm() {
    if (this.data4Login.valid) {
      this.rolesService.getLoginJWT(
        this.data4Login.controls.name.value!,
        this.data4Login.controls.password.value!,
        this.data4Login.controls.roleId.value!).subscribe(
        (jwt: string) => {
          localStorage.setItem('jwt', jwt); // 存储JWT到localStorage
          // 现在你可以发起请求到相关，JWT会自动添加到请求头中
          this.router.navigate(['mymenu']);
        },
        (error) => {
          console.error('登录失败:', error);
        }
      );
    }
  }
}
